<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\VerificationCode;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class RegisterStepController extends Controller
{
    public function step1(Request $request)
    {
        try {
            $validated = $request->validate([
                'email' => 'required|email|unique:users'
            ]);

            // 生成验证码
            $verificationCode = mt_rand(100000, 999999);
            
            // 将验证码存储到缓存中，设置5分钟过期
            Cache::put('verification_code_' . $validated['email'], $verificationCode, now()->addMinutes(5));

            // 发送验证码邮件
            Mail::to($validated['email'])->send(new VerificationCode($verificationCode));

            return response()->json([
                'success' => true,
                'message' => '验证码已发送到您的邮箱'
            ]);

        } catch (\Exception $e) {
            \Log::error('Registration step1 error:', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'success' => false,
                'message' => '发送失败：' . $e->getMessage()
            ], 500);
        }
    }

    public function verifyCode(Request $request)
    {
        $validated = $request->validate([
            'email' => 'required|email',
            'code' => 'required|string'
        ]);

        $cachedCode = Cache::get('verification_code_' . $validated['email']);

        if (!$cachedCode || $cachedCode != $validated['code']) {
            return response()->json([
                'success' => false,
                'message' => '验证码无效或已过期'
            ], 422);
        }

        return response()->json([
            'success' => true,
            'message' => '验证成功'
        ]);
    }

    public function register(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);

        $user = User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
            'attribute_id' => 1  // 修改为默认普通用户权限 ID 1
        ]);

        // 自动登录新用户
        auth()->login($user);

        return redirect()->route('home')
            ->with('success', '注册成功！');
    }
} 